package com.example.myapplication.ui.home;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;

import java.util.List;

public class CourseAdapter extends BaseAdapter {
    private Context context;
    private List<Course> courses;

    public CourseAdapter(Context context, List<Course> courses) {
        this.context = context;
        this.courses = courses;
    }

    @Override
    public int getCount() {
        return courses.size();
    }

    @Override
    public Object getItem(int position) {
        return courses.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_course, parent, false);
            holder = new ViewHolder();
            holder.courseImage = convertView.findViewById(R.id.courseImage);
            holder.courseTitle = convertView.findViewById(R.id.courseTitle);
            holder.courseInstructor = convertView.findViewById(R.id.courseInstructor);
            holder.courseDifficulty = convertView.findViewById(R.id.courseDifficulty);
            holder.courseRating = convertView.findViewById(R.id.courseRating);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Course course = courses.get(position);

        // 加载图片
        Glide.with(context)
                .load(course.getImageUrl())
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.error_image)
                .into(holder.courseImage);

        holder.courseTitle.setText(course.getTitle());
        holder.courseInstructor.setText("讲师: " + course.getInstructor());
        holder.courseDifficulty.setText("难度: " + course.getDifficulty());
        holder.courseRating.setText("评分: " + course.getRating());

        return convertView;
    }

    static class ViewHolder {
        ImageView courseImage;
        TextView courseTitle;
        TextView courseInstructor;
        TextView courseDifficulty;
        TextView courseRating;
    }
}